home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / c / matrixc.zip / NSOLVE.C < prev   
C/C++ Source or Header  |  1990-05-10  |  1KB  |  65 lines

  1. /* Solves equations in n unknowns */
  2. /* Written by Nigel Salt */
  3.  
  4. #include <stdio.h>
  5. double d[4][5]=
  6. {
  7.   6,1,6,6,50,
  8.   1,6,6,0,31,
  9.   0,3,2,1,16,
  10.   8,6,1,9,59
  11. };
  12. double *pd=&d[0][0];
  13.  
  14. int nsolve(int rows,double *data);
  15.  
  16. main()
  17. {
  18.   int i,j;
  19.   nsolve(4,pd);
  20.   for (i=0;i<4;i++)
  21.     {
  22.         printf("\n%6.2lf%6.2lf%6.2lf%6.2lf%6.2lf",\
  23.       d[i][0],d[i][1],d[i][2],d[i][3],d[i][4]);
  24.  
  25.     }
  26.  
  27.  
  28. }
  29. int nsolve(rows,data)
  30. int rows;
  31. double *data;
  32. {
  33.   int i,j,k;
  34.   int cols;
  35.   cols=rows+1;
  36.   for (i=0;i<rows;i++)
  37.     {
  38.     if (*(data+i*cols+i)==0.0)
  39.       {
  40.       fprintf(stderr,"\nnsolve error - singular matrix");
  41.       return 1;
  42.       }
  43.         for (j=cols-1;j>=0;j--)
  44.       {
  45.             *(data+i*cols+j) /= *(data+i*cols+i);
  46.       }
  47.     for (j=i+1;j<rows;j++)
  48.       {
  49.             for (k=cols-1;k>=i;k--)
  50.         *(data+j*cols+k)-=*(data+j*cols+i) * *(data+i*cols+k);
  51.       }
  52.         }
  53.     for (i=rows-2;i>=0;i--)
  54.         {
  55.         for (j=cols-2;j>i;j--)
  56.             {
  57.             *(data+i*cols+cols-1)-= \
  58.             *(data+i*cols+j) * *(data+j*cols+cols-1);
  59.             *(data+i*cols+j)=0;
  60.             }
  61.         }
  62.   return 0;
  63. }
  64.  
  65.